package com.shopping.controller;

import com.shopping.bean.*;
import com.shopping.service.IOrderService;
import com.shopping.service.impl.OrderService;
import com.shopping.util.LayData;
import com.shopping.util.Page;
import com.shopping.util.SYS;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("order")
public class OrderController {

    @Autowired
    OrderService orderService;

    @RequestMapping("submit")
    @ResponseBody
    public Map<String, Object> submitOrder(@RequestBody Map<String, Object> orderData, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            User loginUser = (User) session.getAttribute(SYS.SHOPPING_LOGIN_USER);
            if (loginUser == null) {
                result.put("code", 401);
                result.put("msg", "请先登录");
                return result;
            }
            int userId = loginUser.getUserid();
            orderData.put("userId", userId);
            orderService.submitOrder(orderData);
            result.put("code", 200);
            result.put("msg", "订单提交成功");
        } catch (Exception e) {
            e.printStackTrace(); // 打印异常堆栈信息
            result.put("code", 500);
            result.put("msg", "订单提交失败，请稍后重试");
        }
        return result;
    }


    @GetMapping("list")
    @ResponseBody
    public Map<String, Object> getOrdersByUserId(HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            User loginUser = (User) session.getAttribute(SYS.SHOPPING_LOGIN_USER);
            if (loginUser == null) {
                result.put("code", 401);
                result.put("msg", "请先登录");
                return result;
            }
            int userId = loginUser.getUserid();
            List<Order> orders = orderService.getOrdersByUserId(userId);
            result.put("code", 200);
            result.put("data", orders);
            result.put("msg", "查询订单列表成功");
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code", 500);
            result.put("msg", "查询订单列表失败，请稍后重试");
        }
        return result;
    }

    @RequestMapping("info/{orderId}")
    @ResponseBody
    public Map<String, Object> getOrderInfosByOrderId(@PathVariable("orderId") int orderId) {
        Map<String, Object> result = new HashMap<>();
        try {
            List<Orderinfo> orderInfos = orderService.getOrderInfosByOrderId(orderId);
            result.put("code", 200);
            result.put("data", orderInfos);
            result.put("msg", "查询订单详情成功");
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code", 500);
            result.put("msg", "查询订单详情失败，请稍后重试");
        }
        return result;
    }

    @RequestMapping("delete")
    @ResponseBody
    public LayData delete(Integer id) {
        return LayData.success(200,"删除成功",orderService.delete(id));
    }

    @RequestMapping("addOrderAddress")
    @ResponseBody
    public LayData  addOrderAddress(OrderAddress orderAddress){
        return LayData.success(200,"添加地址成功",orderService.addOrderAddress(orderAddress));
    }
    @RequestMapping("payment")
    @ResponseBody
    public LayData payment(Integer id){
        String code=orderService.payment(id);
        System.out.println(code);
        return LayData.success(200,"",code);
    }
    @RequestMapping("paymentsuccess")
    @ResponseBody
    public LayData paymentSuccess(@RequestParam HashMap map){

        try {
            System.out.println(map);
            orderService.paymentSuccess(map);
            return LayData.success(200, "");
        } catch (Exception e) {
            e.printStackTrace();
            return LayData.success(500, "处理回调数据时出现异常");
        }
    }

    @RequestMapping("getOrderstate")
    @ResponseBody
    public LayData getOrderState(Integer id){
        Order order=orderService.getOrderByID(id);
        return LayData.success(200,"",order.getStatus());
    }

    @RequestMapping("getOrders")
    @ResponseBody
    public LayData getOrders(Page page,String text){
        List<Order> list=orderService.getOrders(page,text);
        int count=orderService.getCount(text);
        return  new LayData(count,list);
    }

    private static final List<String> VALID_STATUS = Arrays.asList("待付款", "已付款", "商家已发货", "已收货", "已完成订单");

    @RequestMapping("update")
    @ResponseBody
    public LayData updateOrder(@RequestBody OrderUpdateDTO orderUpdateDTO) {
        try {
            // 验证订单状态
            String status = orderUpdateDTO.getStatus();
            if (!VALID_STATUS.contains(status)) {
                return LayData.success(400, "无效的订单状态，请选择合法的状态", null);
            }
            orderService.updateOrder(orderUpdateDTO);
            return LayData.success(200, "订单信息修改成功", null);
        } catch (Exception e) {
            e.printStackTrace();
            return LayData.success(500, "订单信息修改失败，请稍后重试", null);
        }
    }

    @RequestMapping("updateStatus")
    @ResponseBody
    public Map<String, Object> updateOrderStatus(@RequestBody OrderUpdateStatusDTO dto) {
        Map<String, Object> response = new HashMap<>();
        try {
            boolean success = orderService.updateOrderStatus(dto);
            if (success) {
                response.put("code", 200);
                response.put("msg", "订单状态更新成功");
            } else {
                response.put("code", 500);
                response.put("msg", "订单状态更新失败，未找到对应的订单");
            }
        } catch (Exception e) {
            response.put("code", 500);
            response.put("msg", "订单状态更新失败: " + e.getMessage());
        }
        return response;
    }
}

